<?php

/**
 * crpVideo
 *
 * @copyright (c) 2007-2008, Daniele Conca
 * @link http://code.zikula.org/projects/crpvideo Support and documentation
 * @author Daniele Conca <conca.daniele@gmail.com>
 * @license GNU/GPL - v.2.1
 * @package crpVideo
 */

Loader :: includeOnce('modules/crpVideo/pnclass/crpVideo.php');

/**
 * the main administration function
 *
 * @return string HTML output
 */
function crpVideo_admin_main()
{
	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::Video', '::', ACCESS_EDIT))
	{
		return LogUtil :: registerPermissionError();
	}

	// Create output object
	$pnRender = pnRender :: getInstance('crpVideo', false);

	// Return the output that has been generated by this function
	return $pnRender->fetch('crpvideo_admin_main.htm');
}

/**
 * add new item
 *
 * @return string HTML output
 */
function crpVideo_admin_new()
{
	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::Video', '::', ACCESS_EDIT))
	{
		return LogUtil :: registerPermissionError();
	}

	// Create output object
	$pnRender = pnRender :: getInstance('crpVideo', false);

	// load the categories system
	if (!($class = Loader :: loadClass('CategoryRegistryUtil')))
		pn_exit('Unable to load class [CategoryRegistryUtil] ...');
	$mainCat = CategoryRegistryUtil :: getRegisteredModuleCategory('crpVideo', 'crpvideos', 'Main', '/__SYSTEM__/Modules/crpVideo');
	$pnRender->assign('mainCategory', $mainCat);
	$pnRender->assign(pnModGetVar('crpVideo'));

	// Return the output that has been generated by this function
	return $pnRender->fetch('crpvideo_admin_new.htm');
}

/**
 * create a video
 * @param 'title' the title of the video
 * @param 'content' the content of the video
 * @param 'language' the language of the video
 */
function crpVideo_admin_create()
{
	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::', '::', ACCESS_EDIT))
	{
		return LogUtil :: registerPermissionError();
	}
	// Confirm authorisation code
	if (!SecurityUtil :: confirmAuthKey())
	{
		return LogUtil :: registerAuthidError(pnModURL('crpVideo', 'admin', 'view'));
	}

	$video = FormUtil :: getPassedValue('video', null, 'POST');
	$video_image = FormUtil :: getPassedValue('video_image', null, 'FILES');
	if ($video['source'] == 'video')
	{
		$video_file = FormUtil :: getPassedValue('video_file', null, 'FILES');
		$newVideoName = time() . '_' . str_replace(" ", "_", $video_file['name']);
		$video['urlvideo'] = pnGetBaseUrl() . pnModGetVar('crpVideo', 'upload_path') . '/' . $newVideoName;
		$video['pathvideo'] = pnModGetVar('crpVideo', 'upload_path') . '/' . $newVideoName;
		$video['file'] = $video_file;
		$video['external'] = null;
	}
	elseif ($video['source'] == 'external')
	{
		$video['urlvideo'] = null;
		$video['pathvideo'] = null;
	}

	$videoObj = new crpVideo();

	$video['image'] = $video_image;

	// Argument check
	if (!$videoObj->dao->validateData($video))
		return false;

	// Create the video
	$videoid = pnModAPIFunc('crpVideo', 'admin', 'create', $video);

	if ($video_image['error'] == UPLOAD_ERR_OK && $videoid)
	{
		$video_image['videoid'] = $videoid;
		$video_image['document_type'] = 'image';
		$id_image = $videoObj->dao->setFile($video_image);
		if ($id_image == '-1')
			return false;
	}

	if ($video_file['error'] == UPLOAD_ERR_OK && $videoid && $video['source'] == 'video')
	{
		Loader :: loadClass('FileUtil');
		$msg = FileUtil :: uploadFile('video_file', pnModGetVar('crpVideo', 'upload_path'), $newVideoName);
		chmod(pnModGetVar('crpVideo', 'upload_path') . '/' . $newVideoName, 0755);
	}

	// The return value of the function is checked
	if ($videoid != false)
	{
		// Success
		LogUtil :: registerStatus(_CREATESUCCEDED);
	}

	return pnRedirect(pnModURL('crpVideo', 'admin', 'view'));
}

/**
 * modify a video
 *
 * @param 'videoid' the id of the item to be modified
 * @return string HTML output
 */
function crpVideo_admin_modify($args)
{
	$videoid = FormUtil :: getPassedValue('videoid', isset ($args['videoid']) ? $args['videoid'] : null, 'GET');
	$objectid = FormUtil :: getPassedValue('objectid', isset ($args['objectid']) ? $args['objectid'] : null, 'GET');

	if (!empty ($objectid))
	{
		$videoid = $objectid;
	}

	// Get the video
	$item = pnModAPIFunc('crpVideo', 'user', 'get', array (
		'videoid' => $videoid
	));
	//die('<pre>'.print_r($item,1).'</pre>');
	if ($item == false)
	{
		return LogUtil :: registerError(_NOSUCHITEM, 404);
	}

	$imageObj = new crpVideo();
	$item['image'] = $imageObj->dao->getFile($videoid, 'image');

	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::', "$item[title]::$videoid", ACCESS_EDIT))
	{
		return LogUtil :: registerPermissionError();
	}

	// Create output object
	$pnRender = pnRender :: getInstance('crpVideo', false);

	// load the categories system
	if (!($class = Loader :: loadClass('CategoryRegistryUtil')))
		pn_exit('Unable to load class [CategoryRegistryUtil] ...');
	$mainCat = CategoryRegistryUtil :: getRegisteredModuleCategory('crpVideo', 'crpvideos', 'Main', '/__SYSTEM__/Modules/crpVideo');
	$pnRender->assign('mainCategory', $mainCat);
	$pnRender->assign(pnModGetVar('crpVideo'));

	// assign the item to the template
	$pnRender->assign($item);

	// Return the output that has been generated by this function
	return $pnRender->fetch('crpvideo_admin_modify.htm');
}

/**
 * update video
 *
 * @param 'videoid' the id of the video
 * @param 'title' the title of the video
 * @param 'content' the content of the video
 * @param 'language' the language of the video
 */
function crpVideo_admin_update()
{
	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::', "::", ACCESS_EDIT))
	{
		return LogUtil :: registerPermissionError();
	}
	// Confirm authorisation code
	if (!SecurityUtil :: confirmAuthKey())
	{
		return LogUtil :: registerAuthidError(pnModURL('crpVideo', 'admin', 'view'));
	}

	$video = FormUtil :: getPassedValue('video', null, 'POST');
	$video_image = FormUtil :: getPassedValue('video_image', null, 'FILES');
	if ($video['source'] == 'video')
	{
		$video_file = FormUtil :: getPassedValue('video_file', null, 'FILES');

		if ($video_file['error'] == UPLOAD_ERR_OK && $video['videoid'])
		{
			$newVideoName = time() . '_' . str_replace(" ", "_", $video_file['name']);
			$video['urlvideo'] = pnGetBaseUrl() . pnModGetVar('crpVideo', 'upload_path') . '/' . $newVideoName;
			$video['pathvideo'] = pnModGetVar('crpVideo', 'upload_path') . '/' . $newVideoName;
		}
		$video['external'] = null;
	}
	elseif ($video['source'] == 'external')
	{
		$video['urlvideo'] = null;
		$video['pathvideo'] = null;
	}

	$videoObj = new crpVideo();

	// retrieve old values
	$oldData = $videoObj->dao->getData($video);

	$video['image'] = $video_image;
	$video['file'] = $video_file;

	// Argument check
	if (!$videoObj->dao->validateData($video))
		return false;

	if (!empty ($video['objectid']))
	{
		$video['videoid'] = $video['objectid'];
	}

	// Update the video
	if (pnModAPIFunc('crpVideo', 'admin', 'update', $video))
	{
		// Success
		LogUtil :: registerStatus(_UPDATESUCCEDED);
	}

	if ($video_image['error'] == UPLOAD_ERR_OK && $video['videoid'])
	{
		$imageObj = new crpVideo();
		$video['image'] = $video_image;
		$imageObj->createCover($video);
	}

	if ($video_file['error'] == UPLOAD_ERR_OK && $video['videoid'] && $video['source'] == 'video')
	{
		Loader :: loadClass('FileUtil');
		if ($video['urlvideo'] != $oldData['urlvideo'])
		{
			unlink($oldData['pathvideo']);
		}

		$msg = FileUtil :: uploadFile('video_file', pnModGetVar('crpVideo', 'upload_path'), $newVideoName);
		chmod(pnModGetVar('crpVideo', 'upload_path') . '/' . $newVideoName, 0755);
	}

	return pnRedirect(pnModURL('crpVideo', 'admin', 'view'));
}

/**
 * delete item
 *
 * @param 'videoid' the id of the video
 * @param 'confirmation' confirmation that this item can be deleted
 * @return mixed string HTML output if no confirmation otherwise true
 */
function crpVideo_admin_delete($args)
{
	$videoid = FormUtil :: getPassedValue('videoid', isset ($args['videoid']) ? $args['videoid'] : null, 'REQUEST');
	$objectid = FormUtil :: getPassedValue('objectid', isset ($args['objectid']) ? $args['objectid'] : null, 'REQUEST');
	$confirmation = FormUtil :: getPassedValue('confirmation', null, 'POST');
	if (!empty ($objectid))
	{
		$videoid = $objectid;
	}

	// Get the existing video
	$item = pnModAPIFunc('crpVideo', 'user', 'get', array (
		'videoid' => $videoid
	));

	if ($item == false)
	{
		return LogUtil :: registerError(_NOSUCHITEM, 404);
	}

	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::Item', "$item[title]::$videoid", ACCESS_DELETE))
	{
		return LogUtil :: registerPermissionError();
	}

	// Check for confirmation.
	if (empty ($confirmation))
	{
		// No confirmation yet
		// Create output object
		$pnRender = pnRender :: getInstance('crpVideo', false);

		// Add a hidden field for the item ID to the output
		$pnRender->assign('videoid', $videoid);
		$pnRender->assign('item', $item);

		// Return the output that has been generated by this function
		return $pnRender->fetch('crpvideo_admin_delete.htm');
	}

	// If we get here it means that the user has confirmed the action

	// Confirm authorisation code
	if (!SecurityUtil :: confirmAuthKey())
	{
		return LogUtil :: registerAuthidError(pnModURL('crpVideo', 'admin', 'view'));
	}

	// Delete the video
	if (pnModAPIFunc('crpVideo', 'admin', 'delete', array (
			'videoid' => $videoid
		)))
	{
		// Success
		LogUtil :: registerStatus(_DELETESUCCEDED);
	}

	return pnRedirect(pnModURL('crpVideo', 'admin', 'view'));
}

/**
 * view items
 *
 * @param int $startnum the start item id for the pager
 * @return string HTML output
 */
function crpVideo_admin_view()
{
	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::', '::', ACCESS_EDIT))
	{
		return LogUtil :: registerPermissionError();
	}

	// Get parameters from whatever input we need.
	$startnum = (int) FormUtil :: getPassedValue('startnum', isset ($args['startnum']) ? $args['startnum'] : null, 'GET');
	$category = FormUtil :: getPassedValue('videos_category', null);
	$active = FormUtil :: getPassedValue('events_status', null);
	$clear = FormUtil :: getPassedValue('clear');
	if ($clear)
	{
		$category = null;
		$active = null;
	}

	// Create output object
	$pnRender = pnRender :: getInstance('crpVideo', false);

	// get all module vars
	$modvars = pnModGetVar('crpVideo');

	// load the category registry util
	if (!($class = Loader :: loadClass('CategoryRegistryUtil')))
	{
		pn_exit('Unable to load class [CategoryRegistryUtil] ...');
	}
	$mainCat = CategoryRegistryUtil :: getRegisteredModuleCategory('crpVideo', 'crpvideos', 'Main', '/__SYSTEM__/Modules/crpVideo');

	// Get all matching pages
	$items = pnModAPIFunc('crpVideo', 'admin', 'getall', array (
		'startnum' => $startnum,
		'numitems' => $modvars['itemsperpage'],
		'ignoreml' => true,
		'category' => $category,
		'mainCat' => $mainCat,
		'active' => $active
	));

	if (!$items)
		$items = array ();

	$rows = array ();
	foreach ($items as $key => $item)
	{
		$options = array ();
		$options[] = array (
			'url' => pnModURL('crpVideo',
			'user',
			'display',
			array (
				'videoid' => $item['videoid']
			)
		), 'image' => 'demo.gif', 'title' => _VIEW);
		if (SecurityUtil :: checkPermission('crpVideo::Video', "$item[title]::$item[videoid]", ACCESS_EDIT))
		{
			$options[] = array (
				'url' => pnModURL('crpVideo',
				'admin',
				'modify',
				array (
					'videoid' => $item['videoid']
				)
			), 'image' => 'xedit.gif', 'title' => _EDIT);
			if (SecurityUtil :: checkPermission('crpVideo::Video', "$item[title]::$item[videoid]", ACCESS_DELETE))
			{
				$options[] = array (
					'url' => pnModURL('crpVideo',
					'admin',
					'delete',
					array (
						'videoid' => $item['videoid']
					)
				), 'image' => '14_layer_deletelayer.gif', 'title' => _DELETE);
			}
		}

		// Add the calculated menu options to the item array
		$item['options'] = $options;
		$rows[] = $item;
	}

	// Assign the items to the template
	$pnRender->assign('videos', $rows);
	$pnRender->assign('videos_category', $category);
	$pnRender->assign('mainCategory', $mainCat);
	$pnRender->assign($modvars);
	$pnRender->assign('lang', pnUserGetLang());
	$pnRender->assign('videos_status', $active);

	// Assign the information required to create the pager
	$pnRender->assign('pager', array (
		'numitems' => pnModAPIFunc('crpVideo',
		'user',
		'countitems',
		array (
			'category' => $category
		)
	), 'itemsperpage' => $modvars['itemsperpage']));

	// Return the output that has been generated by this function
	return $pnRender->fetch('crpvideo_admin_view.htm');
}

/**
 * modify module configuration
 *
 * @return string HTML output string
 */
function crpVideo_admin_modifyconfig()
{
	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::', '::', ACCESS_ADMIN))
	{
		return LogUtil :: registerPermissionError();
	}

	$video = new crpVideo();
	return $video->modifyConfig();
}

/**
 * This is a standard function to update the configuration parameters of the
 * module given the information passed back by the modification form
 */
function crpVideo_admin_updateconfig()
{
	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::', '::', ACCESS_ADMIN))
	{
		return LogUtil :: registerPermissionError();
	}

	$video = new crpVideo();
	return $video->updateConfig();
}

/**
 * delete item's file
 *
 * @param int $videoid item identifier
 * 
 * @return mixed string HTML output if no confirmation otherwise true
 */
function crpVideo_admin_delete_image($args)
{
	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::', '::', ACCESS_DELETE))
	{
		return LogUtil :: registerPermissionError();
	}

	$videoid = FormUtil :: getPassedValue('videoid', null, 'GET');
	$file_type = FormUtil :: getPassedValue('file_type', null, 'GET');

	$imageObj = new crpVideo();
	if ($imageObj->dao->deleteFile($file_type, $videoid))
		LogUtil :: registerStatus(_DELETESUCCEDED);

	return pnRedirect(pnModURL('crpVideo', 'admin', 'view'));
}

/**
 * modify item status
 * 
 * @return string HTML output
 */
function crpVideo_admin_change_status()
{
	// Security check
	if (!SecurityUtil :: checkPermission('crpVideo::', '::', ACCESS_ADD))
	{
		return LogUtil :: registerPermissionError();
	}

	$video = new crpVideo();
	return $video->changeStatus();
}
?>